<?php
/**
 * 配送员
 */

namespace app\api\controller;

use app\admin\model\User;
use app\admin\model\User as UserModel;
use app\common\controller\Api;
use app\common\model\AgentShop;
use app\common\model\ShipOrder;
use app\common\model\ShipRemind;
use think\Db;
use app\common\model\PostMan as PostmanModel;

class Postman extends Api
{
	
	/**
	 * 配送员主页
	 */
	public function index()
	{
		$userId = $this->auth->id;
		$row = Db::name('postMan')->alias('p')
			->join('agentShop a', 'p.agent_id = a.id', 'left')
			->where(['p.user_id' => $userId, 'p.status' => PostmanModel::STATUS_NORMAL])
			->field('p.id, p.name, p.mobile, a.role, a.area')
			->find();
		!$row && $this->error('你不是配送员');
		
		$this->success('查询成功', $row);
	}
	
	/**
	 * 代理的配送员列表
	 */
	public function all()
	{
		$userId = $this->auth->id;
		$level = $this->auth->level;
		
		if($level == User::LEVEL_HEADQUARTERS) {
			$agentId = 0;
		} elseif ($level == \app\admin\model\User::LEVEL_USER) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if (!$adminLevel || $adminLevel['role'] == \app\admin\model\User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$agentInfo = AgentShop::getInfoByUserId($userId);
			if (!$agentInfo || $agentInfo['status'] == AgentShop::STATUS_D) {
				$this->error('代理身份已禁用');
			}
			
			$agentId = $agentInfo['id'];
		}
		
		
		
		$where['agent_id'] = $agentId;
		$status = $this->request->post('status');
		if ($status) {
			$where['status'] = $status;
		} else {
			$where['status'] = ['neq', PostmanModel::STATUS_DISABLED];
		}
		
		$list = Db::name('postMan')
			->where($where)
			->field('id, name, mobile, status')
			->order(['create_time' => 'desc'])
			->select();
		
		$this->success('查询成功', $list);
	}
	
	
	/**
	 * 添加编辑资料
	 */
	public function edit()
	{
		$postData = $this->request->post();
		$check = new \app\common\validate\PostMan();
		if (!$check->check($postData)) {
			$this->error($check->getError());
		}
		
		if (empty($postData['id']) && empty($postData['uid'])) {
			$this->error('请通过分享进来');
		}
		
		$level = $this->auth->level;
		if($level != User::LEVEL_USER) {
			$this->error('你已经有其它代理身份');
		}
		
		$model = new PostmanModel();
		$userId = $this->auth->id;
		//新增
		if (empty($postData['id'])) {
			$recommendUser = User::get($postData['uid']);
			if($recommendUser['level'] == User::LEVEL_HEADQUARTERS) {
				$agentId = 0;
			} else {
				$agent = AgentShop::getInfoByUserId($postData['uid']);
				if (!$agent || $agent['status'] == AgentShop::STATUS_D) {
					$this->error('分享代理不存在');
				}
				$agentId = $agent['role'];
			}
			
			
			$postData['agent_id'] = $agentId;
			$postData['status'] = $model::STATUS_APPLY;
			$postData['user_id'] = $userId;
			//查找是否已经是配送员了
			$postRow = PostmanModel::get(['user_id' => $userId, 'status' => PostmanModel::STATUS_NORMAL]);
			
			if ($postRow) {
				$this->error('你已经是配送员了');
			}
			
			//查看是否已经填写过这个人的资料了
			$row = PostmanModel::get(['user_id' => $userId, 'agent_id' => $agentId]);
			if($row){
				$postData['id'] = $row['id'];
				if ($row['status'] == $model::STATUS_NORMAL) {
					unset($postData['status']);
				}
				$res = $model->allowField(true)->save($postData, ['id' => $row['id']]);
			} else {
				$res = $model->allowField(true)->isUpdate(false)->save($postData);
			}
			
			//更改其它状态为删除
			
			$model = new PostmanModel();
			$updateRes = $model->save(['status' => $model::STATUS_DISABLED], ['user_id' => $userId, 'agent_id' => ['neq', $agentId]]);
			
		} else {
			//编辑
			$res = $model->allowField(true)->save($postData, ['id' => $postData['id']]);
		}
		
		if ($res !== false) {
			$this->success('保存成功' . (!empty($postData['status']) && $postData['status'] == $model::STATUS_APPLY ? ',等待审核!' : ''));
		} else {
			$this->error('保存出错');
		}
		
	}
	
	
	/**
	 * 更改状态
	 */
	public function changeStatus()
	{
		$id = $this->request->get('id');
		$status = $this->request->get('status');
		if (!$id || !$status) {
			$this->error('参数错误');
		}
		
		if($this->auth->level == User::LEVEL_HEADQUARTERS) {
			$agentId = 0;
		} else {
			$agent = AgentShop::getInfoByUserId($this->auth->id);
			!$agent && $this->error('你不是代理');
			
			$agentId = $agent['id'];
		}
		
		$model = new PostmanModel();
		$res = $model
			->save(
				['status' => $status],
				['id' => $id, 'agent_id' => $agentId]);
		
		if ($res !== false) {
			$this->success('操作成功');
		} else {
			$this->error('操作出错');
		}
	}
	
	
	/**
	 * 配送订单
	 */
	public function order()
	{
		$page = $this->request->post('page', 1, 'intval');
		$userId = $this->auth->id;
		$postmans = Db::name('postMan')->where(['user_id' => $userId])
			->column('agent_id', 'id');
		
		$orders = [];
		if($postmans) {
			$where['o.postman_id'] = ['in', array_keys($postmans)];
			
			$status = $this->request->post('status');
			
			$model = new ShipOrder();
			$orders = $model->getOrder($page, '', '', array_keys($postmans), $status);
		}

		
		$this->success('查询成功', $orders);
	}
	
	/**
	 * 取货
	 */
	public function sign()
	{
		$id = $this->request->post('id', '', 'intval');
		$code = $this->request->post('code', '', 'intval');
		if (!$id || !$code) {
			$this->error('参数错误');
		}
		
		$postman = Db::name('postMan')
			->where(['user_id' => $this->auth->id, 'status' => PostmanModel::STATUS_NORMAL])
			->find();
		!$postman && $this->error('你不是配送员');
		
		$model = new ShipOrder();
		$row = $model->find($id);
		!$row && $this->error('订单不存在');
		
		if ($row['status'] != $model::STATUS_SHIPPING) {
			$this->error('非待取货订单');
		}
		
		$row['postman_id'] != $postman['id'] && $this->error('不是你的订单');
		
		$row['send_code'] != $code && $this->error('取件码错误');
		
		$res = $model->save([
			'status' => $model::STATUS_WAIT
		], ['id' => $id]);
		if ($res) {
			$this->success('取件成功');
		} else {
			$this->error('取件失败，请稍候重试');
		}
	}
	
	/**
	 * 获取归属的代理下级及库存（深圳战区）
	 */
	public function getSonAndStock()
	{
		$userId = $this->auth->id;
		$row = Db::name('postMan')->alias('p')
			->join('agentShop a', 'p.agent_id = a.id', 'left')
			->where(['p.user_id' => $userId, 'p.status' => PostmanModel::STATUS_NORMAL])
			->field('p.id, p.agent_id, p.name, p.mobile, a.role, a.area')
			->find();
		
		if (!$row || $row['area'] != UserModel::AREA_SZ || $row['role'] != UserModel::LEVEL_THEATER) {
			$this->error('没有权限');
		}
		
		
		$agents = Db::name('agentShop')->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->where([
				'a.status' => AgentShop::STATUS_Y,
				'a.theater_id' => $row['agent_id'],
				'role' => ['in', [UserModel::LEVEL_WAREHOUSE, UserModel::LEVEL_CENTER]]
			])
			->field('a.role, a.id, a.name, a.address, u.area, u.reward_number')
			->select();
		
		if ($agents) {
			$roleList = UserModel::$levelList;
			foreach ($agents as &$agent) {
				$agent['name'] = '【' . $roleList[$agent['role']] . '】' . $agent['name'];
			}
		}
		
		$stockModel = new \app\common\model\AgentStock();
		$stockList = $stockModel->getStockByAgentId($row['agent_id']);
		
		$this->success('查询成功', [
			'sons' => $agents,
			'stockList' => $stockList
		]);
	}
	
	
	/**
	 * 代理及代理管理员的发货
	 */
	public function send()
	{
		$userId = $this->auth->id;
		$row = Db::name('postMan')->alias('p')
			->join('agentShop a', 'p.agent_id = a.id', 'left')
			->where(['p.user_id' => $userId, 'p.status' => PostmanModel::STATUS_NORMAL])
			->field('p.id, p.agent_id, p.name, p.mobile, a.role, a.area')
			->find();
		
		if (!$row || $row['area'] != UserModel::AREA_SZ || $row['role'] != UserModel::LEVEL_THEATER) {
			$this->error('没有权限');
		}
		
		$postData = $this->request->post();
		$check = new \app\common\validate\ShipOrder();
		if (!$check->check($postData)) {
			$this->error($check->getError());
		}
		
		
		$numberList = $postData['number_list'];
		$sendAgent = AgentShop::get(['id' => $row['agent_id']]);
		
		
		$signAgent = AgentShop::get($postData['agent_id']);
		!$signAgent && $this->error('收货下级不存在');
		
		$postData['postman_id'] = $row['id'];
		
		$model = new \app\common\model\ShipOrder();
		$postmanId = $postData['postman_id'] ?? '';
		$destoryNumber = $postData['destroy_number'] ?? 0;
		$res = $model->sendGoods($signAgent['area'], $postData['ship_name'], $postData['ship_no'], $numberList,
			$signAgent, $sendAgent, $postmanId, $destoryNumber, true);
		
		
		if ($res) {
			$this->success('发货成功');
		} else {
			$this->error($model->getError());
		}
		
		
	}
	
	/**
	 * 获取应发数量
	 */
	public function getSendNumber() {
		$agentId = $this->request->post('agent_id');
		!$agentId && $this->error('参数错误');
		
		$rows = Db::name('shipRemind')
			->where(['agent_id' => $agentId, 'status' => ShipRemind::STATUS_WAIT_SEND])
			->field('id, goods_id, spec_id, number')
			->select();
		$this->success('查询成功', $rows);
	}
}
